package com.llxwz.controller;

import com.google.code.kaptcha.Producer;

import com.llxwz.service.UserService;
import com.llxwz.util.CommunityConstant;
import com.llxwz.util.CommunityUtil;
import com.llxwz.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Controller
public class LoginController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private Producer producer;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private RedisTemplate redisTemplate;

    //去登录页面
    @GetMapping("/login")
    public String toLogin(){
        return "site/login";
    }

    //验证码
    //改进
    @GetMapping("/kaptcha")
    public void kaptcha(HttpServletResponse response) {
        //生成验证码
        String text = producer.createText();//生成的字符
        BufferedImage image = producer.createImage(text);//生成图片

        //将验证码存入session(已改进)
        //session.setAttribute("kaptcha",text);

        //临时给验证码弄个归属
        String kaptchaOwner = CommunityUtil.generateUUID();
        Cookie cookie = new Cookie("kaptchaOwner",kaptchaOwner);
        cookie.setMaxAge(60);//60s后失效
        cookie.setPath(contextPath);
        response.addCookie(cookie);
        //将验证码存入Redis
        String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        redisTemplate.opsForValue().set(redisKey,text,60, TimeUnit.SECONDS);//60s失效


        //将图片输出给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image,"png",os);
        } catch (IOException e) {
            logger.error("响应验证码失败"+e.getMessage());
        }

    }



    //登录验证
    @PostMapping("/login")
    public String login(String username, String password, String code, boolean remember,
                        Model model,/*HttpSession session,*/HttpServletResponse response,
                        @CookieValue(value = "kaptchaOwner",defaultValue = "")String kaptchaOwner){

        //检查验证码
        //String kaptcha = (String) session.getAttribute("kaptcha");(已改进)
        String kaptcha =null;

        if(StringUtils.isNoneBlank(kaptchaOwner)){
            String redisKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
            kaptcha = (String) redisTemplate.opsForValue().get(redisKey);
        }

        if (StringUtils.isBlank(kaptcha)
                || StringUtils.isBlank(code)
                || !kaptcha.equalsIgnoreCase(code)){//忽略大小写
            model.addAttribute("codeMsg","验证码不正确");
            return "site/login";
        }

        //检查账号密码
        int expiredSeconds = remember ? REMEMBER_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.login(username, password, expiredSeconds);
        //说明登陆成功
        if (map.containsKey("ticket")){
            Cookie cookie = new Cookie("ticket",map.get("ticket").toString());
            cookie.setPath(contextPath);
            cookie.setMaxAge(expiredSeconds);
            response.addCookie(cookie);

            return "redirect:/index";
        }else{
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));

            return "site/login";
        }



    }

    @PostMapping("/sendMail")
    @ResponseBody
    public String sendMail(String email, HttpServletResponse response){

        Map<String, Object> map = userService.sendMail(email);
        if(map.containsKey("mailCode")){

            String mailCode =String.valueOf(map.get("mailCode"));
            Cookie cookie = new Cookie("mailCode", mailCode);
            cookie.setMaxAge(120);//60s后失效
            cookie.setPath(contextPath);
            response.addCookie(cookie);
            //将验证码存入Redis
            String redisKey = RedisKeyUtil.getMailCodeKey(mailCode);
            redisTemplate.opsForValue().set(redisKey,mailCode,120, TimeUnit.SECONDS);//60s失效

            return CommunityUtil.getJsonString(0,"发送成功");
        }else{
            return CommunityUtil.getJsonString(1, String.valueOf(map.get("emailMsg")));
        }

    }

    @PostMapping("/mailLogin")
    public String mailLogin(String email, String code, boolean remember,
                            Model model,HttpServletResponse response,
                            @CookieValue("mailCode")String mailCode){

        String mc =null;

        if(StringUtils.isNoneBlank(mailCode)){
            String redisKey = RedisKeyUtil.getMailCodeKey(mailCode);
            mc = (String) redisTemplate.opsForValue().get(redisKey);
        }

        if (StringUtils.isBlank(mc)
                || StringUtils.isBlank(code)
                || !mc.equals(code)){
            model.addAttribute("codeMsg","验证码不正确");
            return "site/mailLogin";
        }


        //检查账号密码
        int expiredSeconds = remember ? REMEMBER_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.mailLogin(email,expiredSeconds);
        //说明登陆成功
        if (map.containsKey("ticket")){
            Cookie cookie = new Cookie("ticket",map.get("ticket").toString());
            cookie.setPath(contextPath);
            cookie.setMaxAge(expiredSeconds);
            response.addCookie(cookie);

            return "redirect:/index";
        }else{
            model.addAttribute("mailMsg",map.get("mailMsg"));
            return "site/mailLogin";
        }
    }

    @GetMapping("/logout")
    public String logout(@CookieValue("ticket")String ticket){
        userService.loginOut(ticket);
        SecurityContextHolder.clearContext();
        //重定向默认是get请求
        return "redirect:/login";
    }

}
